import { onMounted, reactive, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  foodMenImport,
  foodMenuExport,
  getCanteenList,
  queryMenuList,
  delMenu,
  delMutMenu,
  foodWeekDown,
  foodWeekSubmit,
} from "../../api/canteen/menu-managerApi";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import fileDownload from "js-file-download";
export default function menuManger() {
  const searchForm = reactive({});
  const router = useRouter();
  const optionValue = ref("");
  const option = ref([]);
  const totalNum = ref("");
  const pageSize = ref(50);
  const pageNum = ref(1);

  //导入
  function info() {
    importDialogVisible.value = true;
  }

  function edit(row) {
    router.push({
      name: "MenuEdit",
      query: {
        id: row.id ? row.id : "",
      },
    });
  }
  //新增功能
  function addFood() {
    router.push({
      name: "MenuEdit",
      query: {
        id: 1,
      },
    });
  }

  //获取菜谱分页信息
  function getFoodData() {
    queryMenuList({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    }).then((res) => {
      tableData.value = res.data.content;
      totalNum.value = res.data.totalElements;
    });
  }

  //获取食堂列表数据
  function getCanteenData() {
    getCanteenList().then((res) => {
      option.value = res.data;
    });
  }

  const fileList = ref([]);
  const infoForm = reactive({});
  const tableData = ref([]);
  const importDialogVisible = ref(false);
  const route = useRoute();
  watch(
    () => route.path,
    () => {
      if (route.path === "/canteen/menu-manger") getFoodData();
    }
  );

  const importFormRef = ref(null);
  //导入提交
  function submitImport() {
    const loading = ElLoading.service({
      lock: true,
      text: "文件上传中，请稍等...",
      background: "rgba(0, 0, 0, 0.7)",
    });
    let formData = new FormData();
    formData.append("canteenId", infoForm.region);
    formData.append("startTime", infoForm.time);
    fileData.value.map((item, index) => {
      formData.append("file", fileData.value[index]);
    });
    foodMenImport(formData)
      .then(() => {
        importDialogVisible.value = false;
        importFormRef.value.resetFields();
        loading.close();
        fileList.value = [];
        getFoodData();
      })
      .catch(() => {
        loading.close();
      });
  }
  function cancelImport() {
    importDialogVisible.value = false;
    importFormRef.value.resetFields();
    fileList.value = [];
  }
  // 关闭导入对话框的回调
  function handleClose() {
    cancelImport();
  }
  //删除数据
  function del(id) {
    ElMessageBox.confirm("您确定要删除这条数据么?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        delMenu(id).then(() => {
          ElMessage({
            message: "删除成功",
            type: "success",
          });
          getFoodData();
        });
      })
      .catch(() => {
        ElMessage({
          message: "取消操作",
          type: "info",
        });
      });
  }

  //跳转到详情页面
  function toDetail(id) {
    router.push({
      name: "MenuDetail",
      query: {
        id: id,
      },
    });
  }

  const searchRef = ref(null);

  //搜索
  function search() {
    queryMenuList({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      canteenId: searchForm.canteen,
      startTime: searchForm.startTime,
      endTime: searchForm.endTime,
      status: searchForm.status,
    }).then((res) => {
      tableData.value = res.data.content;
      totalNum.value = res.data.totalElements;
    });
  }

  //重置
  function reset() {
    searchRef.value.resetFields();
    getFoodData();
  }
  const multipleTable = ref([]);
  function handleSelectionChange(val) {
    multipleTable.value = val;
  }
  //导出
  function exportMenu() {
    if (multipleTable.value.length === undefined) {
      ElMessage.info("请先选择需要导出的数据");
      return;
    } else if (multipleTable.value.length > 1) {
      ElMessage.info("只能选择一条数据");
    } else {
      foodMenuExport({
        id: multipleTable.value[0].id,
      }).then((res) => {
        fileDownload(res, "本周菜谱数据.xls");
        ElMessage.success("导出成功");
      });
    }
  }
  // 全选删除
  function delMultipleTable() {
    if (multipleTable.value.length !== undefined) {
      ElMessageBox.confirm("您确定要删除这条数据么?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const ids = [];
          multipleTable.value.map((item) => {
            ids.push(item.id);
          });
          delMutMenu(ids).then(() => {
            ElMessage({
              message: "删除成功",
              type: "success",
            });
            getFoodData();
          });
        })
        .catch(() => {
          ElMessage.info("取消操作");
        });
    } else {
      ElMessage.warning("请先选择需要删除的数据");
    }
  }
  const limitNum = ref(1);
  //文件超出个数限制时的钩子
  function exceedFile(files, fileList) {
    ElMessage.error(
      `只能选择 ${limitNum.value}个文件，当前共选择了 ${
        files.length + fileList.length
      } 个`
    );
  }
  // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
  function beforeUploadFile(file) {
    let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
    let size = file.size / 1024 / 1024;
    if (extension !== "xls") {
      ElMessage.warning("只能上传后缀是.xls的文件");
    }
    if (size > 10) {
      ElMessage.warning("文件大小不得超过10M");
    }
  }
  const fileData = ref([]);
  // 文件上传成功时的钩子
  function handleSuccess(file, fileList) {
    fileData.value.push(fileList.raw);
    ElMessage.success("文件上传成功");
  }
  // 文件上传失败时的钩子
  function handleError(err, file, fileList) {
    console.log(err, file, fileList);
    ElMessage.error("文件上传失败");
  }
  //导出文件
  const exportForm = ref({});
  const exportRef = ref(null);
  const exportDialogVisible = ref(false);
  function cancelExport() {
    exportDialogVisible.value = false;
    exportRef.value.resetFields();
  }
  // 批量提交操作
  function multipleSubmit() {
    const ids = [];
    if (multipleTable.value.length === undefined) {
      ElMessage.warning("请选择数据后再试！");
    } else {
      multipleTable.value.map((item) => {
        ids.push(item.id);
      });
      foodWeekSubmit(ids)
        .then(() => {
          ElMessage.success("提交成功");
          getFoodData();
        })
        .catch((err) => {
          ElMessage.error(err.msg);
        });
    }
  }
  // 批量下架菜谱
  function menuDown() {
    if (multipleTable.value.length !== undefined) {
      const muData = multipleTable.value.filter((item) => item.status === 4);
      if (muData.length === 0) {
        ElMessage.warning("只能删除在售中的数据");
      } else {
        const ids = [];
        muData.map((item) => {
          ids.push(item.id);
        });
        foodWeekDown(ids).then((res) => {
          if (res.code === 200) {
            ElMessage.success("下架成功");
            getFoodData();
          }
        });
      }
    } else {
      ElMessage.warning("请选择数据后再试！");
    }
  }
  // 单条数据下架
  function signMenuDown(id) {
    const ids = [];
    ids.push(id);
    foodWeekDown(ids).then((res) => {
      if (res.code === 200) {
        ElMessage.success("下架成功");
        getFoodData();
      }
    });
  }
  //菜谱状态数据
  const menuStatus = ref([
    {
      label: "待提交",
      value: 1,
    },
    {
      label: "待审核",
      value: 2,
    },
    {
      label: "已下架",
      value: 3,
    },
    {
      label: "在售中",
      value: 4,
    },
    {
      label: "驳回",
      value: 5,
    },
  ]);

  onMounted(() => {
    getFoodData();
    getCanteenData();
  });
  return {
    multipleSubmit,
    exportRef,
    exportForm,
    exportDialogVisible,
    cancelExport,
    getFoodData,
    exportMenu,
    searchForm,
    optionValue,
    addFood,
    fileList,
    infoForm,
    info,
    del,
    importDialogVisible,
    tableData,
    option,
    edit,
    pageNum,
    pageSize,
    totalNum,
    submitImport,
    handleSuccess,
    toDetail,
    search,
    searchRef,
    reset,
    delMultipleTable,
    multipleTable,
    handleSelectionChange,
    limitNum,
    exceedFile,
    beforeUploadFile,
    handleError,
    importFormRef,
    cancelImport,
    menuStatus,
    menuDown,
    signMenuDown,
    handleClose,
  };
}
